//
//  MBRefreshGifHeaderLottie.m
//  Meboo
//
//  Created by kyo on 2024/3/7.
//

#import "MBRefreshGifHeaderLottie.h"

#import <AudioToolbox/AudioToolbox.h>
#import "Meboo-Swift.h"
@interface MBRefreshGifHeaderLottie ()
@property(nonatomic, strong) MJLottieView *loadingView;
@property(nonatomic, copy) NSString *jsonString;
@end
@implementation MBRefreshGifHeaderLottie

- (instancetype)init
{
    if (self = [super init])
    {
        self.lastUpdatedTimeLabel.hidden = YES;
        self.stateLabel.hidden = YES;
    }
    return self;
}

- (MJLottieView *)loadingView {
    if (!_loadingView) {
        _loadingView = [MJLottieView new];
        [_loadingView defultSetWithName:self.jsonString];
        _loadingView.frame = CGRectMake(ScreenWidth/2 - 25, 0, 50, 50);
//        _loadingView.frame = CGRectMake(0, 0, 50, 50);
        _loadingView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _loadingView;
}

- (void)setJsonName:(NSString *)jsonName
{
    self.jsonString = jsonName;
    [self addSubview:self.loadingView];
}

#pragma mark - innerMethod
- (void)beginRefreshing
{
    if (@available(iOS 10.0, *))
    {
        UIImpactFeedbackGenerator *impactLight = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
        [impactLight impactOccurred];
    }
    else
    {
        AudioServicesPlaySystemSound(1502);
    }
    [super beginRefreshing];
}

#pragma mark - 监听控件的刷新状态
- (void)setState:(MJRefreshState)state
{
    MJRefreshCheckState;
    if (self.jsonString.length > 0)
    {
        switch (state)
        {
            case MJRefreshStateIdle: /// 普通闲置状态
            {
                [self.loadingView stopAnimation];
                break;
            }
            case MJRefreshStatePulling:
            {
                break;
            }
            case MJRefreshStateRefreshing:
            {
                [self.loadingView startAnimation];
                break;
            }
            default:
                break;
        }
    }
}

#pragma mark - 实时监听控件 scrollViewContentOffset
- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
{
    [super scrollViewContentOffsetDidChange:change];
    if (self.jsonString.length > 0)
    {
        CGPoint point;
        id newVelue = [change valueForKey:NSKeyValueChangeNewKey];
        [(NSValue *)newVelue getValue:&point];
        
        self.loadingView.hidden = !(self.pullingPercent);
        CGFloat progress = point.y / (ScreenHeight/3.0);
        if (self.state != MJRefreshStateRefreshing)
        {
            [self.loadingView resetProgressWithProgress:-progress];
        }
    }
}
@end
